module mux #(
    parameter DATA_SIZE = 8,
    parameter NUM = 8
) (
    input [NUM*DATA_SIZE-1:0] din,
    input [NUM-1:0] sel,
    output [DATA_SIZE-1:0] dout
);
assign dout = mux_prio(din,sel);

function [DATA_SIZE-1:0] mux_prio;
    input [NUM*DATA_SIZE-1:0] din;
    input [NUM-1:0] sel;
    reg [NUM-1:0] dat;
    integer i,j;

    begin
        for (i = 0;i < DATA_SIZE;i=i+1) begin
            for (j = 0;j < NUM ;j=j+1 ) begin
                dat[j] = din[j*DATA_SIZE+i];
            end
            mux_prio[i] = mux_prio_bit(dat,sel_prio(sel));
        end    
    end
endfunction

function [NUM-1:0] sel_prio ;
    input [NUM-1:0] sel;
    reg temp;
    integer i,j;
    begin
        sel_prio[0] = sel[0];
        for(i=1;i<NUM;i=i+1)
            begin
                temp = 0;
                for(j=0;j<i;j=j+1)
                    begin
                        temp = temp | sel[j];
                    end
                sel_prio[i] = sel[i] && !temp;
            end    
    end
endfunction

function     mux_prio_bit ;

    input  [NUM-1:0]  din;
    input  [NUM-1:0]  sel;
    integer i;
    begin
        mux_prio_bit = din[0]&&sel[0];
        for(i=1;i<NUM;i=i+1)
            mux_prio_bit = mux_prio_bit | (din[i]&sel[i]);    
    end
endfunction


endmodule